AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

include("shared.lua")

--models/prop_c17/pottery03a.mdl

 
function ENT:Initialize() 
	
	self:SetModel( "models/props/bed_body_reference.mdl" )
	
	self.NextUse =0
	
	--self:PhysicsInitBox(Vector(-15,-15,0),Vector(15,15,5))
	self:SetMoveType( MOVETYPE_NONE ) 
	self:SetSolid( SOLID_VPHYSICS )
	
	self:SetMaterial("models/props/bed_body_reference.vtx")
	
   local phys = self.Entity:GetPhysicsObject()
   if (phys:IsValid()) then
   phys:Wake()
   end
end 

function ENT:SpawnFunction(pl,tr)
	if !tr.Hit then return end
	local t = ents.Create("spawn_beacon")
	
	local a = tr.HitNormal:Angle()
	a.p = a.p - 90
	t:SetAngles(a)
	t:SetPos(tr.HitPos + tr.HitNormal * 5)
	
	if tr.HitWorld then
	else
		t:SetParent(tr.Entity)
	end
	
	t:Spawn()
	t:Activate()
	undo.Create("spawn_beacon")
		undo.AddEntity(t)
		undo.SetPlayer(pl)
	undo.Finish()
	
	SetSpawnBeacon(pl,t)
end

function ENT:Use( activator, caller )
	if self.NextUse > CurTime() then return end
	self.NextUse = CurTime() + 2
   	
	activator:EmitSound("buttons/button5.wav",200,100)
	SetSpawnBeacon(activator,self)
end

function ENT:OnRemove()
end

function SetSpawnBeacon(player,beacon)
	
	if beacon == nil then
		player:PrintMessage( HUD_PRINTTALK, "Spawn Reset, you will now spawn normaly" )  
	else
		player:PrintMessage( HUD_PRINTTALK, "Spawn beacon selected, you will now spawn at this beacon, type !resetspawn to spawn normaly" )  
	end
	
	player.SpawnBeacon = beacon
	if beacon == nil then
		player:SendLua("LocalPlayer().SpawnBeacon = nil")
	else
		player:SendLua("LocalPlayer().SpawnBeacon = ents.GetByIndex("..beacon:EntIndex()..")")
	end
end

function ENT:SpawnPlayer(player)

	if(self:Blocked()) then
		player:PrintMessage( HUD_PRINTTALK, "Cannot spawn at beacon, beacon blocked" ) 
	else
		player:SetPos(self:GetPos() + self:GetUp() * -32)
		player:PrintMessage( HUD_PRINTTALK, "Spawning at beacon" ) 
		player:EmitSound("ambient/machines/teleport1.wav",300,100)
	end
	
end

local function SelectSpawn(player)
	if player.SpawnBeacon and player.SpawnBeacon:IsValid() then
		player.SpawnBeacon:SpawnPlayer(player)
	end
end
hook.Add("PlayerSpawn","BeaconSpawnSelect",SelectSpawn)

local function resetSpawn( ply, saywhat )
	if saywhat == "!resetspawn" then
		SetSpawnBeacon(ply,nil)
	end
end
hook.Add ( "PlayerSay", "resetSpawn", resetSpawn ) 


local function protectBeacon(player,entity) 
	if entity:GetClass() == "spawn_beacon" then return false end
	return true
end
hook.Add("PhysgunPickup", "protectBeacon", protectBeacon)
